package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2023-12-02 09:21
 */
@Slf4j
@Component("1002")
public class TrackStrategy implements PaidRecordStrategy {
    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    /**
     * 处理购买类型是:声音
     * @param userPaidRecordVo
     */
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("[用户服务]处理购买类型是声音");
        //2.处理声音购买记录
        //2.1 业务去重避免同一订单多次新增购买记录
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(queryWrapper);
        if (count > 0) {
            return;
        }
        //2.2 构建用户购买声音对象（可能存在多条购买项）
        //远程调用专辑服务获取声音信息得到所属专辑ID
        TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        userPaidRecordVo.getItemIdList().forEach(trackId -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setTrackId(trackId);
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            //2.3 保存用户购买记录记录
            userPaidTrackMapper.insert(userPaidTrack);
        });
    }
}
